package impl

import (
	"context"
	"errors"

	"gitee.com/hexug/devcloud/mcenter/apps/token"
	"gitee.com/hexug/devcloud/mcenter/apps/token/provider"
	"gitee.com/hexug/devcloud/mcenter/common/validate"
	"go.mongodb.org/mongo-driver/bson"
)

func (i *implServer) ValidateToken(ctx context.Context, in *token.ValidateTokenRequest) (*token.Token, error) {
	if err := validate.V().Struct(in); err != nil {
		return nil, err
	}

	filter := bson.M{"_id": in.AccessToken}
	res := i.Col.FindOne(ctx, filter)
	if res.Err() != nil {
		return nil, res.Err()
	}
	t := &token.Token{}
	if err := res.Decode(t); err != nil {
		return nil, err
	}
	//校验状态
	if err := t.CheckStatus(); err != nil {
		return nil, err
	}
	//校验用户
	if err := t.CheckToken(in); err != nil {
		return nil, err
	}
	return t, nil
}

func (i *implServer) IssueToken(ctx context.Context, in *token.IssueTokenRequest) (*token.Token, error) {
	if err := in.Validate(); err != nil {
		return nil, err
	}
	pv := provider.Get(in.GrantType)
	if pv == nil {
		return nil, errors.New("供应商获取失败，未注册Issuer")
	}
	tk, err := pv.IssuerToken(ctx, in)
	if err != nil {
		return nil, err
	}
	//写入数据库
	_, err = i.Col.InsertOne(ctx, tk)
	if err != nil {
		return nil, err
	}
	return tk, nil
}

func (i *implServer) DeleteToken(ctx context.Context, in *token.DeleteTokenRequest) (*token.Token, error) {
	if err := validate.V().Struct(in); err != nil {
		return nil, err
	}
	//检查该token是否存在
	filter := bson.M{"_id": in.AccessToken}
	res := i.Col.FindOne(ctx, filter)
	if res.Err() != nil {
		return nil, res.Err()
	}
	t := &token.Token{}
	if err := res.Decode(t); err != nil {
		return nil, err
	}
	vr := token.NewValidateTokenRequest(in.Username)
	vr.AccessToken = in.AccessToken
	if err := t.CheckToken(vr); err != nil {
		return nil, err
	}
	//存在的话就删除
	if _, err := i.Col.DeleteOne(ctx, filter); err != nil {
		return nil, err
	}
	return t, nil
}
